package cn.minis.beans.factory;

import cn.minis.beans.BeansException;
import cn.minis.beans.processor.AutowiredAnnotationBeanPostProcessor;

import java.util.ArrayList;
import java.util.List;


/**
 * Autowired 注入的 Bean
 */
public class AutowireCapableBeanFactory extends AbstractBeanFactory {
  
  
  private final List<AutowiredAnnotationBeanPostProcessor> beanPostProcessors =
    new ArrayList<>();
  
  public void addBeanPostProcessor(AutowiredAnnotationBeanPostProcessor
    beanPostProcessor) {
    this.beanPostProcessors.remove(beanPostProcessor);
    this.beanPostProcessors.add(beanPostProcessor);
  }
  public int getBeanPostProcessorCount() {
    return this.beanPostProcessors.size();
  }
  public List<AutowiredAnnotationBeanPostProcessor> getBeanPostProcessors() {
    return this.beanPostProcessors;
  }
  
  @Override
  public Object applyBeanPostProcessorBeforeInitialization(Object existingBean, String beanName) throws BeansException {
    Object result = existingBean;
  
    for (AutowiredAnnotationBeanPostProcessor beanProcessor : getBeanPostProcessors()) {
      beanProcessor.setBeanFactory(this);
      result = beanProcessor.postProcessBeforeInitialization(result, beanName);
      if (result == null) {
        return result;
      }
    }
  
    return result;
  }
  
  @Override
  public Object applyBeanPostProcessorAfterInitialization(Object existingBean, String beanName) throws BeansException {
    return null;
  }
}
